﻿namespace MicroCloud.AspNetCore
{
    /// <summary>
    /// <see cref="IApplicationBuilder"/> 辅助扩展方法
    /// </summary>
    public static class ApplicationBuilderExtensions
    {
        /// <summary>
        /// 框架初始化
        /// <para>适用于AspNetCore环境</para>
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static WebApplication UseMicroCloud(this WebApplication app)
        {
            IServiceProvider provider = app.Services;
            ILogger logger = provider.GetLogger(typeof(ApplicationBuilderExtensions));

            logger.LogInformation("开始执行系统框架初始化");

            Stopwatch watch = Stopwatch.StartNew();

            // 输出注入服务的日志
            StartupLogger startupLogger = provider.GetService<StartupLogger>();
            startupLogger?.Output(provider);

            PackBase[] packs = provider.GetAllPacks();
            logger.LogInformation("获取到 {length} 个模块(Pack)需要加载", packs.Length);
            foreach (PackBase pack in packs)
            {
                Type packType = pack.GetType();
                string packDescription = packType.GetDescription();
                if (pack is AspPackBase aspPack)
                {
                    aspPack.UsePack(app);
                }
                else
                {
                    pack.UsePack(provider);
                }
                logger.LogInformation("模块 {name}[{description}] 加载完成", packType.Name, packDescription);
            }

            watch.Stop();
            logger.LogInformation("系统框架初始化完成，耗时：{elapsed}。", watch.Elapsed);

            //使用 URL Rewrite 中间件实现 HTTP 重定向到 HTTPS
            //var options = new RewriteOptions().AddRedirectToHttpsPermanent();
            //app.UseRewriter(options);

            //打印一个MicroCloud的启动彩蛋
            ConsoleHelper.WriteLine($@"
                    _                  ___ _                 _     _                 __     _     ___               
              /\/\ (_) ___ _ __ ___   / __\ | ___  _   _  __| |   /_\  ___ _ __   /\ \ \___| |_  / __\___  _ __ ___ 
             /    \| |/ __| '__/ _ \ / /  | |/ _ \| | | |/ _` |  //_\\/ __| '_ \ /  \/ / _ \ __|/ /  / _ \| '__/ _ \
            / /\/\ \ | (__| | | (_) / /___| | (_) | |_| | (_| |_/  _  \__ \ |_) / /\  /  __/ |_/ /__| (_) | | |  __/
            \/    \/_|\___|_|  \___/\____/|_|\___/ \__,_|\__,_(_)_/ \_/___/ .__/\_\ \/ \___|\__\____/\___/|_|  \___|
                                                                          |_|                                       
            ", ConsoleColor.DarkRed);

            ConsoleHelper.WriteLine($@"                      科技改变未来 · 数据传承价值                   
            ", ConsoleColor.DarkYellow);

            return app;
        }

        /// <summary>
        /// 添加MVC并Area路由支持
        /// </summary>
        /// <param name="app"></param>
        /// <param name="area"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseMvcWithAreaRoute(this IApplicationBuilder app, bool area = true)
        {
            return app.UseMvc(builder =>
            {
                if (area)
                {
                    builder.MapRoute("area", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                }
                builder.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
        }

        /// <summary>
        /// 添加Endpoint并Area路由支持
        /// </summary>
        /// <param name="endpoints"></param>
        /// <param name="area"></param>
        /// <returns></returns>
        public static IEndpointRouteBuilder MapControllersWithAreaRoute(this IEndpointRouteBuilder endpoints, bool area = true)
        {
            if (area)
            {
                endpoints.MapControllerRoute(
                    name: "areas-router",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            }

            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            return endpoints;
        }

    }
}